//
//  Utils.swift
//  BridgeHousePeople
//
//  Created by 松松 on 2018/5/17.
//  Copyright © 2018年 ZRQ. All rights reserved.
//

import Foundation
//import SAMKeychain
import AVFoundation
import CoreMedia
import UIKit
import CoreImage

////MARK:获取设备号
//func getDeviceIdentifier() -> String?{
//    let appName = Bundle.main.infoDictionary![String(kCFBundleNameKey)] as! String
//    var appUUID = SAMKeychain.password(forService: appName, account: "incoding")
//    if appUUID == nil{
//        appUUID = UIDevice.current.identifierForVendor?.uuidString
//        let query = SAMKeychainQuery()
//        query.service = appName
//        query.account = "incoding"
//        query.password = appUUID
//        query.synchronizationMode = SAMKeychainQuerySynchronizationMode.no
//        do{
//            try query.save()
//        }catch{
//            print("uuid弄失败了")
//        }
//    }
//    return appUUID
//}

//MARK:判断是否为空 如果是空 弹出提示
infix operator ???
public func ???<T>(optional: T?, message: String) -> Bool{
    if optional == nil{
        Toast.showMessage(message)
        return true 
    }
    if optional is String && optional as! String == ""{
        Toast.showMessage(message)
        return true
    }
    return false
}


public func ssFunc(_ block:()->Void){
    #if DEBUG
    block()
    #endif
}

//MARK:验证输入的是否是数字
public func validateNumber(number:String) -> Bool{
    let tmpSet = "0123456789."
    for item in number{
        if !tmpSet.contains(item){
            return false
        }
    }
    return true
}

//MARK:判断字符串是否为空
public func theStringEmpty(string : String?) ->Bool{
    if string == nil || string!.isEmpty{
        return true
    }else{
        return false
    }
}

//MARK:获取当前的ViewController
public func currentViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
    if let nav = base as? UINavigationController {
        return currentViewController(base: nav.visibleViewController)
    }
    if let tab = base as? UITabBarController {
        return currentViewController(base: tab.selectedViewController)
    }
    if let presented = base?.presentedViewController {
        return currentViewController(base: presented)
    }
    return base
}


//MARK:视频转码
public func transformMoive(inputPath:String,outputPath:String,success:@escaping (URL)->Void) {


    let avAsset:AVURLAsset = AVURLAsset(url: URL.init(fileURLWithPath: inputPath), options: nil)
    let assetTime = avAsset.duration

    let duration = CMTimeGetSeconds(assetTime)
    ssPrint("视频时长 \(duration)");
    let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: avAsset)
    if compatiblePresets.contains(AVAssetExportPresetLowQuality) {
        let exportSession:AVAssetExportSession = AVAssetExportSession.init(asset: avAsset, presetName: AVAssetExportPresetMediumQuality)!
        let existBool = FileManager.default.fileExists(atPath: outputPath)
        if existBool {
        }
        exportSession.outputURL = URL.init(fileURLWithPath: outputPath)


        exportSession.outputFileType = AVFileType.mp4
        exportSession.shouldOptimizeForNetworkUse = true;
        exportSession.exportAsynchronously(completionHandler: {

            switch exportSession.status{

            case .failed:

                ssPrint("失败...\(String(describing: exportSession.error?.localizedDescription))")
                break
            case .cancelled:
                ssPrint("取消")
                break
            case .completed:
                ssPrint("转码成功")
                let mp4Path = URL.init(fileURLWithPath: outputPath)
//                self.uploadVideo(mp4Path: mp4Path)
                success(mp4Path)
            default:
                ssPrint("..")
            }
        })
    }
}

//MARK:删除文件
public func delFile(byPath:String){
    let fileManager = FileManager.default
    let isHave = fileManager.fileExists(atPath: byPath)
    if isHave{
        ssPrint("即将删除\(byPath)")
        try! fileManager.removeItem(atPath: byPath)

    }
}

//MARK:获取本地IP
public func GetIPAddresses() -> String? {
    var addresses = [String]()

    var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
    if getifaddrs(&ifaddr) == 0 {
        var ptr = ifaddr
        while (ptr != nil) {
            let flags = Int32(ptr!.pointee.ifa_flags)
            var addr = ptr!.pointee.ifa_addr.pointee
            if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                        if let address = String(validatingUTF8:hostname) {
                            addresses.append(address)
                        }
                    }
                }
            }
            ptr = ptr!.pointee.ifa_next
        }
        freeifaddrs(ifaddr)
    }
    return addresses.first
}


//MARK:复制微信号跳转微信
public func copyAndJumpWechat(wechatStr:String?){
    if wechatStr == nil{
        Toast.showMessage("无微信号")
        return
    }
    let pastboard = UIPasteboard.general
    pastboard.string = wechatStr
    let wechatUrl = URL(string: "weixin://")!
    if UIApplication.shared.canOpenURL(wechatUrl){
        UIApplication.shared.openURL(wechatUrl)
    }else{
        Toast.showMessage("您尚未安装微信")
    }
}

//MARK:打开链接
public func openURl(_ url:String?){
    if url == nil{
        Toast.showMessage("链接地址为空")
        return
    }
    var openUrl : URL?
    let str = url
    if str!.contains("http://"){
        openUrl = URL(string: str!)
    }else{
        openUrl = URL(string: "http://" + str!)
    }
    if openUrl == nil{
        Toast.showMessage("当前链接地址不存在")
    }else{
        UIApplication.shared.openURL(openUrl!)
    }
}

//MARK:打电话
public func call(_ phone:String?){
    if phone == nil{
        Toast.showMessage("无联系方式")
        return
    }
    UIApplication.shared.openURL(URL(string: "telprompt:\(phone!)")!)
}

//MARK:切图九宫格
public typealias ImageArrBlock = ([UIImage]) -> Void
/// - Parameters:
///   - url: 地址
///   - row: 行数
///   - line: 列数
///   - imagesBlock: 回调
public func getImageFrom(image:UIImage,row:Int=3,line:Int=3,imagesBlock:ImageArrBlock?){

    var imageArr = [UIImage]()
    let count = row*line
    let height = image.size.height/CGFloat(row)
    let width = image.size.width/CGFloat(line)
    for i in 0..<count{
        ssPrint(CGFloat(i%line)*width)
        ssPrint(CGFloat(i%row)*height)
        let rect = CGRect(x: CGFloat(i%line)*width, y: CGFloat(i/row)*height, width: width, height: height)
        let image = UIImage(cgImage: image.cgImage!.cropping(to: rect)!)
        imageArr.append(image)
    }
    imagesBlock?(imageArr)

}

//MARK:生成二维码
public func creatQRcodeBy(_ string:String) -> UIImage{

    let filter = CIFilter(name: "CIQRCodeGenerator")
    filter?.setDefaults()
    let data = string.data(using: .utf8)
    filter?.setValue(data, forKey: "inputMessage")
    if let outputImage = filter?.outputImage{
        let qrcodeImage = setupHighDefinitionUIImage(outputImage, size: 300)
        return qrcodeImage
    }
    return UIImage()
}

fileprivate func setupHighDefinitionUIImage(_ image: CIImage, size: CGFloat) -> UIImage {
    let integral: CGRect = image.extent.integral
    let proportion: CGFloat = min(size/integral.width, size/integral.height)

    let width = integral.width * proportion
    let height = integral.height * proportion
    let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
    let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!

    let context = CIContext(options: nil)
    let bitmapImage: CGImage = context.createCGImage(image, from: integral)!

    bitmapRef.interpolationQuality = CGInterpolationQuality.none
    bitmapRef.scaleBy(x: proportion, y: proportion);
    bitmapRef.draw(bitmapImage, in: integral);
    let image: CGImage = bitmapRef.makeImage()!
    return UIImage(cgImage: image)
}



